﻿using Model;
using Model.Xcode;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utilities;
using XCode;

namespace Business
{
    public class DepartmentForDingTalkBll
    {
        /// <summary>
        /// 获取部门列表
        /// </summary>
        public static GetDepartmentList GetDepartmentList()
        {
            LogHelper log = LogFactory.GetLogger("获取部门列表");
            try
            {
                GetDepartmentList model = DepartmentBll.GetList();

                if (model != null)
                {
                    if (model.errcode == 0)
                    {
                        //string json = model.department.ToJson();
                        //Console.Write("成功:\n" + json);
                    }
                    else
                    {
                        log.Error("\r\n DepartmentForDingTalkBll-GetDepartmentList() 新增部门失败,具体原因为：" + model.errmsg + "\r\n");
                        //Console.Write(model.errmsg);
                    }
                }
                else
                {
                    log.Error("\r\n DepartmentForDingTalkBll-GetDepartmentList() 获取部门列表失败,具体原因为：无返回数据\r\n");
                    //Console.Write("无返回数据");
                }

                return model;
            }
            catch (Exception ex)
            {
                log.Error("\r\n DepartmentForDingTalkBll-GetDepartmentList() 获取部门列表失败,具体原因为：" + ex.Message + "\r\n");
                //Console.Write(ex.Message);
                return new GetDepartmentList();
            }
        }

        /// <summary>
        /// 新增部门
        /// </summary>
        /// <param name="name"></param>
        /// <param name="parentid"></param>
        public static void AddDepartment(string name, string parentid,string sourceIdentifier)
        {
            LogHelper log = LogFactory.GetLogger("新增部门");
            try
            {
                DepartmentEntity model = new DepartmentEntity();
                model.name = name;
                model.createDeptGroup = true;
                model.autoAddUser = true;
                model.parentid = parentid;
                model.createDeptGroup = true;
                model.sourceIdentifier = sourceIdentifier;

                DingTalkDepartmentResult Result = DepartmentBll.Create(model);

                if (Result != null)
                {
                    if (Result.Errcode == 0)
                    {
                        log.Debug("\r\n------------------------------------------------新增部门------------------------------------------------\n\n\r\n部门id为:" + Result.id + "\n");
                        //Console.Write("创建成功,ID=" + Result.id);
                    }
                    else
                    {
                        log.Error("\r\n DepartmentForDingTalkBll-AddDepartment() 新增部门失败,具体原因为：" + Result.Errmsg + "\r\n");
                        //Console.Write(Result.errmsg);
                    }
                }
                else
                {
                    log.Error("\r\n DepartmentForDingTalkBll-AddDepartment() 新增部门失败,具体原因为：无返回数据\r\n");
                    //Console.Write("无返回数据");
                }
            }
            catch (Exception ex)
            {
                log.Error("\r\n DepartmentForDingTalkBll-AddDepartment() 新增部门失败,具体原因为：" + ex.Message + "\r\n");
                //Console.Write(ex.Message);
            }
        }

        /// <summary>
        /// 根据V2数据为钉钉新增部门
        /// </summary>
        public static void InsertDepartmentForDingTalk()
        {
            LogHelper log = LogFactory.GetLogger("根据V2数据为钉钉新增部门");
            List<TSysDepartmentinfo> DepartmentList = TSysDepartmentinfo.FindAll(TSysDepartmentinfo._.ID > 0).ToList();
            Stopwatch watch = CommonHelper.TimerStart();

            log.Info("\r\n------------------------------------------------部门数据导入到钉钉------------------------------------------------\r\n");

            #region 循环插入到钉钉
            foreach (var item in DepartmentList)
            {
                var dingTalkDList = GetDepartmentList().department;
                var findParent = dingTalkDList.Where(a => a.sourceIdentifier == item.ParentID).FirstOrDefault();
                var findList = dingTalkDList.Where(a=>a.sourceIdentifier==item.Code).ToList();
                if (findList.Count > 0)
                {
                    log.Error("钉钉部门新增时，DepartmentResult中DepartmentID已存在，DepartmentID=" + item.Code + "; 部门名称=" + item.FullName);
                    //查询数据是否有变动
                    if (item.ParentID != "0")
                    {
                        //值变动
                        if (findList.FirstOrDefault().sourceIdentifier != item.ParentID|| findList.FirstOrDefault().name != item.FullName)
                        {
                            UpdateDepartment(findList.FirstOrDefault().id, item.FullName, findParent.id);
                        }
                    }
                }
                else
                {
                    AddDepartment(item.FullName, item.ParentID == "0" ? "1" : findParent.id, item.Code);
                }
            }
            #endregion

        }

        /// <summary>
        /// 根据钉钉部门id获取部门详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static string GetDepartment(string Id)
        {
            GetDepartment model = new GetDepartment();
            try
            {
                model = DepartmentBll.Get(Id);
                if (model.errcode == "90002")
                {
                    System.Threading.Thread.Sleep(1500);
                    model = DepartmentBll.Get(Id);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return model.ToJson();
        }

        /// <summary>
        /// 删除整个组织架构
        /// </summary>
        public static void DeleteDepartment()
        {
            var dingTalkDList = GetDepartmentList().department;
            foreach (var item in dingTalkDList)
            {
                DeleteDepartment(item.id);
            }
        }
        /// <summary>
        /// 根据钉钉id删除钉钉部门
        /// </summary>
        /// <param name="id"></param>
        public static void DeleteDepartment(string id)
        {
            LogHelper log = LogFactory.GetLogger("DeleteDepartment");
            try
            {
                Result Result = DepartmentBll.Delete(id);

                if (Result != null)
                {
                    if (Result.errcode == "0")
                    {
                        //Console.Write("删除成功," + Result.errmsg);
                    }
                    else
                    {
                        if (Result.errcode != "60003")
                        {
                            log.Error("\r\n DepartmentForDingTalkBll-DeleteDepartment() 根据钉钉id删除钉钉部门失败,具体原因为：" + Result.errmsg + "\r\n");
                        }

                        //Console.Write(Result.errmsg);
                    }
                }
                else
                {
                    log.Error("\r\n DepartmentForDingTalkBll-DeleteDepartment() 根据钉钉id删除钉钉部门失败,具体原因为：无返回数据\r\n");
                    //Console.Write("无返回数据");
                }
            }
            catch (Exception ex)
            {
                log.Error("\r\n DepartmentForDingTalkBll-DeleteDepartment() 根据钉钉id删除钉钉部门失败,具体原因为：" + ex.Message + "\r\n");
                //Console.Write(ex.Message);
            }
        }

        /// <summary>
        /// 更新钉钉部门信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="parentid"></param>
        public static void UpdateDepartment(string id, string name, string parentid)
        {
            LogHelper log = LogFactory.GetLogger("UpdateDepartment");
            try
            {
                string DepartmentJson = GetDepartment(id);

                DepartmentEntity model = new DepartmentEntity();
                model = Newtonsoft.Json.JsonConvert.DeserializeObject<DepartmentEntity>(DepartmentJson);
                model.parentid = parentid;
                model.name = name;

                string param = model.ToJson();

                Result result = DepartmentBll.Update(param);

                if (result != null)
                {
                    if (result.errcode == "0")
                    {
                        //Console.Write("更新成功," + result.errmsg);
                    }
                    else
                    {
                        log.Error("\r\n DepartmentForDingTalkBll-UpdateDepartment() 更新钉钉部门信息失败,具体原因为：" + result.errmsg + "\r\n");
                        //Console.Write(result.errmsg);
                    }
                }
                else
                {
                    log.Error("\r\n DepartmentForDingTalkBll-UpdateDepartment() 更新钉钉部门信息失败,具体原因为：无返回数据\r\n");
                    //Console.Write("无返回数据");
                }
            }
            catch (Exception ex)
            {
                log.Error("\r\n DepartmentForDingTalkBll-UpdateDepartment() 更新钉钉部门信息失败,具体原因为：" + ex.Message + "\r\n");
                //Console.Write(ex.Message);
            }
        }

        /// <summary>
        /// 根据部门id获取部门下所有用户
        /// </summary>
        /// <param name="DepartmentId"></param>
        public static void GetByDepartmentIdForUserInfoList(string DepartmentId)
        {
            LogHelper log = LogFactory.GetLogger("GetByDepartmentIdForUserInfoList");
            GetDepartmentForUserList model = DepartmentBll.GetByDepartmentIdForUserInfoList(DepartmentId);

            if (model != null)
            {
                if (model.errcode == 0)
                {
                    //string json = model.userlist.ToJson();
                    //Console.Write("成功:\n" + json);
                }
                else
                {
                    log.Error("\r\n DepartmentForDingTalkBll-GetByDepartmentIdForUserInfoList() 根据部门id获取部门下所有用户失败,具体原因为：" + model.errmsg + "\r\n");
                    //Console.Write(model.errmsg);
                }
            }
            else
            {
                log.Error("\r\n DepartmentForDingTalkBll-GetByDepartmentIdForUserInfoList() 根据部门id获取部门下所有用户失败,具体原因为：无返回数据\r\n");
                //Console.Write("无返回数据");
            }

        }


        public static void DDUpdate(string DepName)
        {
            GetDepartmentList DepartmentList = DepartmentBll.GetList();

            string TempDDDeptID = DepartmentList.department.Where(e => e.name.Equals(DepName)).ToList().FirstOrDefault().id;

            string DepartmentJson = GetDepartment(TempDDDeptID);

            DepartmentEntity model = new DepartmentEntity();
            model = Newtonsoft.Json.JsonConvert.DeserializeObject<DepartmentEntity>(DepartmentJson);

            model.order = "";
            model.parentid = "49051121";

            string param = model.ToJson();
            Result result = DepartmentBll.Update(param);
            if (result != null)
            {
                if (result.errcode == "0")
                {
                    Console.Write("数据更新成功\r\n");
                }
                else
                {

                    Console.Write("\n更新部门ESBDepartmentId为:" + TempDDDeptID + "， 错误原因：" + result.errmsg + "\n");
                }
            }
            else
            {
                Console.Write("\r\n无返回数据\r\n");
            }
        }
    }
}
